#include "TextScrollBarElement.h"
#include "SDL/SDL_ttf.h"

TextScrollBarElement::TextScrollBarElement(int xPos, int yPos, Widget *parent,
		std::string text, int relY,SDL_Surface* surfaceDefault,SDL_Surface* surfacePressed) :
	Widget(xPos, yPos, parent) {

	this->text = text;

	defaultSurface = surfaceDefault;
	pressedSurface = surfacePressed;

	SDL_Color textColor = { 0, 0, 0 };
	TTF_Font *font = NULL;
	font = TTF_OpenFont(BUTTON_FONT_PATH, 14);

	if (font == NULL) {
		Logger::log("ScrollBarText", "loadSurface", "No se cargó la fuente");
	}

	if (this->text != "") {
		char* c_text = new char[this->text.size() + 1];
		strcpy(c_text, this->text.c_str());
		SDL_Surface* textSurface =
				TTF_RenderText_Solid(font, c_text, textColor);
		delete[] c_text;

		SDL_Rect offset;
		offset.x = 0;
		offset.y = (defaultSurface->h - textSurface->h) / 2;
		offset.w = textSurface->w;
		offset.h = textSurface->h;

		if (SDL_BlitSurface(textSurface, NULL, defaultSurface, &offset) != 0) {
//			Logger::log("Surface", "applySurface", "No se pudo hacer blit");
		}

		if (SDL_BlitSurface(textSurface, NULL, pressedSurface, &offset) != 0) {
//			Logger::log("Surface", "applySurface", "No se pudo hacer blit");
		}
	}

	activeSurface = defaultSurface;
	selected = false;
	parcel = getPosition();
	parcel.height = activeSurface->h;
	parcel.width = activeSurface->w;

	this->minVisibleY = relY;
	this->maxVisibleY = SCROLLTXTPANELH - this->defaultSurface->h + relY;


}

void TextScrollBarElement::handleEvent(Event event) {
	if (!isVisible()) {
		return;
	}

	if (this->mouseOver(event)) {

		if (event.getType() == MouseButtonPressed) {

			if (!this->selected) {
				selected = true;
			}
			else {
				selected = false;
			}
		}
	}
}

void TextScrollBarElement::resolve() {
	if (this->selected) {
		activeSurface = pressedSurface;
	}else{
		activeSurface = defaultSurface;
	}
}

void TextScrollBarElement::showOn(SDL_Surface *surface) {
	if (isVisible()){
		SDL_Rect offset;
		offset.x = parcel.posX;
		offset.y = parcel.posY;
		offset.w = parcel.width;
		offset.h = parcel.height;
		if (SDL_BlitSurface(activeSurface, NULL, surface, &offset) != 0) {
//			Logger::log("Surface", "applySurface", "No se pudo hacer blit");
		}
	}
}

TextScrollBarElement::~TextScrollBarElement() {
	// TODO Implementarrrrrrrrr
}

void TextScrollBarElement::up() {
	parcel.posY -= parcel.height;
}

void TextScrollBarElement::down() {
	parcel.posY += parcel.height;
}

void TextScrollBarElement::setFocus() {
	activeSurface = pressedSurface;
	selected = true;
}

void TextScrollBarElement::unsetFocus() {
	activeSurface = defaultSurface;
	selected = false;
}

void TextScrollBarElement::setYpos(int yPos) {
	parcel.posY = yPos;
}

std::string TextScrollBarElement::getText() {
	return this->text;
}

bool TextScrollBarElement::isVisible() {
	return (parcel.posY < maxVisibleY && parcel.posY >= minVisibleY);
}

bool TextScrollBarElement::isFocused() {
	return selected;
}
